package com.huaxin.hxmodulemqtt.service;

import com.huaxin.feignclient.device.DeviceClient;
import com.huaxin.feignclient.device.models.DeviceDataCollectionWideAddDTO;
import com.huaxin.feignclient.device.models.DeviceInstance;
import com.huaxin.hxmodulemqtt.common.ReflectionUtils;
import com.huaxin.hxmodulemqtt.dto.AecDataReportReqDTO;
import com.huaxin.hxmodulemqtt.dto.DataPoint;
import com.huaxin.hxmodulemqtt.dto.LineData;
import com.huaxin.hxmodulemqtt.mapping.DeviceMetricFieldMapping;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class DataProcessor {

    private final DeviceClient deviceClient;

    /**
     * 处理 AEC 设备数据上报，转换为宽表 DTO 列表
     * 每个 AecDataReportReqDTO 对应一条线路（设备）的数据
     */
    public List<DeviceDataCollectionWideAddDTO> processBatch(AecDataReportReqDTO req) {
        // 1. 获取 LineData
        LineData lineData = req.getLines();
        if (lineData == null || lineData.getData() == null || lineData.getData().isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 获取设备 ID（线路编号）
        Long deviceId = Long.valueOf(lineData.getLine()); // ✅ 正确：getLine()
        DeviceInstance device = deviceClient.queryDeviceInstanceByAutoId(deviceId);
        if (device == null) {
            // 设备不存在，跳过
            return Collections.emptyList();
        }

        // 3. 创建宽表 DTO
        DeviceDataCollectionWideAddDTO dto = new DeviceDataCollectionWideAddDTO();
        dto.setStationNumber(Long.valueOf(req.getIstation()));
        dto.setDeviceType(device.getDeviceType());
        dto.setDeviceId(deviceId);
        // 4. 遍历所有 DataPoint，映射字段
        for (DataPoint point : lineData.getData()) { // ✅ 正确：lineData.getData()
            String metricCode = point.getName(); // 如 "10004"
            dto.setIndexCode(metricCode);
            String fieldName = DeviceMetricFieldMapping.getFieldName(device.getDeviceType(), metricCode);
            if (fieldName != null) {
                try {
                    ReflectionUtils.setFieldValue(dto, fieldName, point.getValue());
                } catch (Exception e) {
                    throw new RuntimeException("设置字段失败 - 字段名: [" + fieldName + "], 值: [" + point.getValue() + "]", e);
                }
            }
        }

        // 5. 返回单个设备的 DTO 列表
        return Collections.singletonList(dto);
    }
}